package com.demo.redis.springbootcache;

import com.demo.redis.entity.User;
import com.demo.redis.springbootcache.annotation.CacheExpire;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * springboot cache
 * 缓存底层使用redis
 * @author cyj
 */
@Service
public class AnnotationCacheServcie {

    /**
     * Cacheable生成策略是cacheNames::key,采用SimpleKeyGenerator生成
     * 这里使用自定义CacheManager，将key生成策略修改cacheNames:key
     * @param userId 用户id
     * @return user对象
     */
    @Cacheable(cacheNames = "user", key = "#userId")
    public User getUserId(Integer userId) {
        return new User().setUserId(userId);
    }

    /**
     * 返回null不缓存
     * @param userId 用户id
     * @return null对象
     */
    @Cacheable(cacheNames = "user", key = "#userId", unless = "#result == null")
    public User returnNull(Integer userId) {
        return null;
    }

    /**
     * 更新缓存
     * @param userId 用户id
     * @return 用户id
     */
    @CachePut(cacheNames = "user", key = "#userId")
    public User updateUser(Integer userId, String name) {
        return new User().setUserId(userId).setName(name);
    }

    /**
     * 删除缓存
     * @param userId 用户id
     */
    @CacheEvict(cacheNames = "user", key = "#userId")
    public void deleteCache(Integer userId) {}

    /**
     * 设置缓存过期
     * @param userId
     */
    @Cacheable(cacheNames = "user", key = "#userId")
    @CacheExpire(5000)
    public User setExpireCache(Integer userId) {
        return new User().setUserId(userId);
    }

    @Cacheable(cacheNames = "user", key = "#name")
    @CacheExpire(16000)
    public User setExpireCache(String name) {
        return new User().setName(name);
    }
}
